package mfuny.ggongal.admin.gift;

import java.io.File;
import java.util.List;
import java.util.Random;

import mfuny.ggongal.admin.Server;
import mfuny.ggongal.admin.debug.Debug;

import org.springframework.web.servlet.ModelAndView;

import com.ibatis.sqlmap.client.SqlMapClient;

public class GiftCardService {
	SqlMapClient sqlMapper;
	ModelAndView mav;
	
	public GiftCardService() throws Exception {
		sqlMapper = Server.getSqlMapper();
		mav = new ModelAndView();
	}
	
	//상품권 등록페이지.
	public ModelAndView regGiftCardForm() throws Exception {
		mav.clear();
		mav.setViewName("/giftCard/regGiftCardForm.ga");
		return mav;
	}
	
	//상품권 등록처리.
	public ModelAndView regGiftCard(GiftCardDao cardDao) throws Exception {
		try{
			sqlMapper.startTransaction();
			cardDao.setCard_img_oriname(cardDao.getCard_img_file().getOriginalFilename());
			cardDao.setCard_img_savname(System.currentTimeMillis() + "_card_" + new Random().nextInt(99) + ".jpg");
			cardDao.setCard_img_capacity(cardDao.getCard_img_file().getSize());
			int result = sqlMapper.update("card_insert", cardDao);
			if(result > 0) {
				cardDao.getCard_img_file().transferTo(new File(Server.filePath + cardDao.getCard_img_savname()));
			}
			
			sqlMapper.commitTransaction();
		}catch(Exception e){
			Debug.toDebugFile(e, "regGiftCard");
		}finally{
			sqlMapper.endTransaction();
		}
		return giftCard();
	}
	
	//모바일 상품권 현황.
	@SuppressWarnings("unchecked")
	public ModelAndView giftCard() throws Exception {
		List<GiftCardDao> cardList = sqlMapper.queryForList("card_selectAll", null);
		mav.clear();
		mav.setViewName("/giftCard/giftCard.ga");
		mav.addObject("cardList", cardList);
		return mav;
	}
}
